package com.wangjiacai.utils.ali.tts;

import com.alibaba.fastjson.JSON;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerResponse;
import com.alibaba.nls.client.transport.ConnectionListener;
import com.wangjiacai.utils.ali.NettyConnection;
import com.wangjiacai.utils.ali.NettySpeechListener;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;


@Data
@Slf4j
public abstract class NettySpeechSynthesizerListener implements NettySpeechListener {

    private NettyConnection nettyConnection;
    private ConnectionListener connectionListener;


    public abstract void onComplete(SpeechSynthesizerResponse var1);

    public void onOpen() {
        log.info("connection is ok");
    }

    public void onClose(int closeCode, String reason) {
        log.info("connection is closed due to {},code:{}", reason, closeCode);
    }

    public void onError(Throwable throwable) {
        log.error("error occurred", throwable);
    }

    public void onMessage(String message) {
        if (message != null && message.trim().length() != 0) {
            log.debug("on message:{}", message);
            SpeechSynthesizerResponse response =JSON.parseObject(message, SpeechSynthesizerResponse.class);
            if (this.isComplete(response)) {
                this.onComplete(response);
            } else if (this.isTaskFailed(response)) {
                this.onFail(response.getStatus(), response.getStatusText());
            } else {
                log.error(message);
            }

        }
    }

    public void onFail(int status, String reason) {
        log.error("fail status:{},reasone:{}", status, reason);
    }

    public abstract void onMessage(ByteBuffer var1);

    private boolean isComplete(SpeechSynthesizerResponse response) {
        String name = response.getName();
        return name.equals("SynthesisCompleted");
    }

    private boolean isTaskFailed(SpeechSynthesizerResponse response) {
        String name = response.getName();
        return name.equals("TaskFailed");
    }

}
